package com.sjgtw.cloud.common.security.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.sjgtw.cloud.common.core.exception.BaseException;
import com.sjgtw.cloud.common.core.exception.CustomException;
import com.sjgtw.cloud.common.core.exception.PreAuthorizeException;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;

/**
 * <p>Title: 全局异常拦截、处理器</p>
 * <p>Description: </p>
 * @author Admin
 * @date 2020-7-1
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 自定义异常--异常基类
	 */
	@ExceptionHandler(BaseException.class)
	public AjaxResult baseException(BaseException e) {
		log.error(e.getMessage(), e);
		return AjaxResult.error(e.getDefaultMessage());
	}

	/**
	 * 用户自定义Custom异常
	 */
	@ExceptionHandler(CustomException.class)
	public AjaxResult businessException(CustomException e) {
		log.error(e.getMessage(), e);
		if (StringUtils.isNull(e.getCode())) {
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.error(e.getCode(), e.getMessage());
	}
	
	/**
	 *  提交或修改的自定义表单数据校验异常
	 */
	@ExceptionHandler(BindException.class)
	public AjaxResult validatedBindException(BindException e) {
		log.error(e.getMessage(), e);
		String message = e.getAllErrors().get(0).getDefaultMessage();
		return AjaxResult.error(message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Object validExceptionHandler(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return AjaxResult.error(message);
	}

	/**
	 * 用户权限类异常
	 */
	@ExceptionHandler(PreAuthorizeException.class)
	public AjaxResult preAuthorizeException(PreAuthorizeException e) {
		return AjaxResult.error("未授权限，请联系管理员！");
	}
	
	/**
	 * 其他不在自定义异常类异常
	 */
	@ExceptionHandler(Exception.class)
	public AjaxResult handleException(Exception e) {
		log.error(e.getMessage(), e);
		return AjaxResult.error(e.getMessage());
	}


}
